#include "xmlconfig.h"

#include <QtXml/QXmlInputSource>
#include <QtXml/QXmlStreamWriter>

const QString ConfigTags::CONFIG = "wl-grafik-config";
const QString ConfigTags::WIN_WIDTH = "win-width";
const QString ConfigTags::WIN_HEIGHT = "win-height";
const QString ConfigTags::LAST_USED_SCHEDULE = "last-used-schedule";
const QString ConfigTags::SCHEDULE_DATE_FORMAT = "MM-yyyy";

/* ************************************************************************************ */

ConfigHandler::ConfigHandler(AppConfig &conf) : config(conf) {
}

ConfigHandler::~ConfigHandler() {
    saveToFile();
}

bool ConfigHandler::startDocument() {
    return true;
}

bool ConfigHandler::endDocument() {
    return true;
}

bool ConfigHandler::startElement(const QString&, const QString&, const QString &qName,
const QXmlAttributes&)
{
    tags.push(qName);
    return true;
}

bool ConfigHandler::endElement(const QString&, const QString&, const QString& qName)
{
    if(qName == tags.top()) {
        tags.pop();
    }
    return true;
}

bool ConfigHandler::characters(const QString &ch) {
    bool ok = false;
    QString val = ch.trimmed();

    if(val.isEmpty()) {
        return true;
    }

    QString currentTag = tags.top();

    if(currentTag == ConfigTags::WIN_WIDTH) {
        config.setWinWidth(val.toInt(&ok));
        if(!ok) {
            qDebug() << "Invalid window width in config. Setting default.";
            config.setWinWidth(DefaultConfig::get().getWinWidth());
        }
    } else if(currentTag == ConfigTags::WIN_HEIGHT) {
        config.setWinHeigth(val.toInt(&ok));
        if(!ok) {
            qDebug() << "Invalid window height in config. Setting default.";
            config.setWinHeigth(DefaultConfig::get().getWinHeigth());
        }
    } else if(currentTag == ConfigTags::LAST_USED_SCHEDULE) {
        config.setLastUsedSchedule(QDate::fromString(val,
            ConfigTags::SCHEDULE_DATE_FORMAT));
        if(!config.getLastUsedSchedule().isValid()) {
            qDebug() << "Invalid date in config. Setting default(current date).";
            config.setLastUsedSchedule(DefaultConfig::get().getLastUsedSchedule());
        }
    }

    return true;
}

bool ConfigHandler::fatalError(const QXmlParseException& exc) {
    qDebug() << exc.message();
    return true;
}

void ConfigHandler::loadFromFile(const QString &path) {
    QFile xmlFile(path);
    if(!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        //TODO throw exception
    } else {
        filePath = path;

        QXmlInputSource src(&xmlFile);

        QXmlSimpleReader reader;
        reader.setContentHandler(this);
        reader.setErrorHandler(this);

        bool ok = reader.parse(src);
        if(!ok) {
            //TODO error
        }

        xmlFile.close();
    }
}

void ConfigHandler::saveToFile() {
    QFile xmlFile(filePath);
    if(!xmlFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        //TODO throw exception
    } else {
        QXmlStreamWriter writer(&xmlFile);
        writer.setAutoFormatting(true);
        writer.writeStartDocument("1.0");

        writer.writeStartElement(ConfigTags::CONFIG);

        writer.writeTextElement(ConfigTags::WIN_WIDTH,
            QString::number(config.getWinWidth()));
        writer.writeTextElement(ConfigTags::WIN_HEIGHT,
            QString::number(config.getWinHeigth()));
        writer.writeTextElement(ConfigTags::LAST_USED_SCHEDULE,
            config.getLastUsedSchedule().toString(ConfigTags::SCHEDULE_DATE_FORMAT));

        writer.writeEndElement();

        writer.writeEndDocument();
        xmlFile.close();
    }
}
